package org.bing.engine.jmx;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bing.engine.common.logging.Log;
import org.bing.engine.common.logging.LogFactory;
import org.bing.engine.core.domain.ContainerInstance;

public class ManagementFactory {
    private static final Log logger = LogFactory.getLog(ManagementFactory.class);
    private Map<String, ManagementProxyClient> proxyClientCache = new HashMap<String, ManagementProxyClient>();
    private VirtualMachineManager vmm;
    private JmxConnectorManager jcm;

    public void setJmxConnectorManager(JmxConnectorManager jcm) {
        this.jcm = jcm;
    }

    public void setVirtualMachineManager(VirtualMachineManager vmm) {
        this.vmm = vmm;
    }

    public List<ManagementProxyClient> getEngineBaseProxyClient() {
        List<LocalVirtualMachine> vms = vmm.getAllLocalVirtualMachine();
        List<ManagementProxyClient> res = new ArrayList<ManagementProxyClient>();
        for (LocalVirtualMachine lvm : vms) {
            String tmpId = null;
            try {
                tmpId = getProperty(lvm, ContainerInstance.INST_GUID_PREFIX);
                if (tmpId != null) {
                    ManagementProxyClient client = new ManagementProxyClient(jcm.getJMXConnector(lvm));
                    res.add(client);
                    proxyClientCache.put(tmpId, client);
                }
            } catch (Exception e) {
                logger.error("Fail to do jmx call! " + e);
            }
        }

        return res;
    }

    public ManagementProxyClient getManagementProxyClient(String guid) {
        ManagementProxyClient client = proxyClientCache.get(guid);
        if (client != null) {
            return client;
        }
        List<LocalVirtualMachine> vms = vmm.getAllLocalVirtualMachine();
        for (LocalVirtualMachine lvm : vms) {
            String tmpId = null;
            try {
                tmpId = getProperty(lvm, ContainerInstance.INST_GUID_PREFIX);
            } catch (Exception e) {
                logger.error("Fail to do jmx call! ", e);
            }
            if (tmpId != null && guid.equals(tmpId)) {
                client = new ManagementProxyClient(jcm.getJMXConnector(lvm));
                proxyClientCache.put(tmpId, client);
                return client;
            }
        }

        return null;
    }

    private String getProperty(LocalVirtualMachine lvm, String key) throws IOException {
        ManagementProxyClient client = new ManagementProxyClient(jcm.getJMXConnector(lvm));
        return client.getRuntimeMXBean().getSystemProperties().get(ContainerInstance.INST_GUID_PREFIX);
    }
}
